﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using ShopBLL;
using ShopModel;
using ASP;

public partial class ProductList : BasePage
{
    #region VARIABLES

    public int CategoryID = 0;
    public int ProducerID = 0;
    public string CategoryName;

    public int Sort = 11;
    public int PageNumber = 1;

    bool afterSearching = false;
    int oldProductOnPage = -1;

    public List<int> ProductsToCompare;

    #endregion VARIABLES

    #region METHODS

    private void BindProduct(ProductSearchCriteria criteria, int pageNumber, int sort)
    {
        if (!afterSearching)
        {
            int productCount = 0;
            int lastIndex = 1;
            int pageSize;

            if (Session["ProductsOnPage"] != null)
                pageSize = Convert.ToInt32(Session["ProductsOnPage"]);
            else
                pageSize = Convert.ToInt32(ddlProductsOnPage.SelectedValue);

            criteria.ProducerId = ProducerID;
            criteria.CategoryId = CategoryID > 0 ? CategoryID : -1;

            List<Products> productList = null;

            switch (sort % 10)
            {
                default:
                case 1:
                    productList = ProductsManager.Instance.SearchProduct(criteria, SortMethod.PriceAscending, ref pageNumber, pageSize, out productCount, true, CommonTools.CurrentLanguageID);
                    break;

                case 2:
                    productList = ProductsManager.Instance.SearchProduct(criteria, SortMethod.PriceDescending, ref pageNumber, pageSize, out productCount, true, CommonTools.CurrentLanguageID);
                    break;

                case 3:
                    productList = ProductsManager.Instance.SearchProduct(criteria, SortMethod.NameAscending, ref pageNumber, pageSize, out productCount, true, CommonTools.CurrentLanguageID);
                    break;

                case 4:
                    productList = ProductsManager.Instance.SearchProduct(criteria, SortMethod.NameDescending, ref pageNumber, pageSize, out productCount, true, CommonTools.CurrentLanguageID);
                    break;
            }

            if (productCount == 0)
            {
                lastIndex = 1;
            }
            else if (productCount % pageSize == 0)
            {
                lastIndex = productCount / pageSize;
            }
            else
            {
                lastIndex = productCount / pageSize + 1;
            }

            Category c = ProductsManager.Instance.GetCategoryByID(CategoryID, CommonTools.CurrentLanguageID);

            if (c == null || (c != null && c.ViewId == null))
            {
                rpProducts.DataSource = productList;
                rpProducts.DataBind();
            }
            else
            {
                GenerateView(productList, c, pnlView);
            }


            lblProductCount.Text = Resources.Language.ProductsCount + ": " + productCount.ToString();

            //ustawienie przełącznika stron

            ctrlPageSwitch.SetProperty(CategoryID, pageNumber, lastIndex, 5, sort);

            if (sort > 10) // po wyszukaniu
            {
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 12, aPriceDec);
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 11, aPriceInc);
            }
            else
            {
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 2, aPriceDec);
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 1, aPriceInc);
            }

            if (sort > 10)
            {
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 14, aNameDec);
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 13, aNameInc);
            }
            else
            {
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 4, aNameDec);
                RenderSortAnchor(CategoryID, ProducerID, pageNumber, 3, aNameInc);
            }
            ddlProductsOnPage.SelectedValue = (string)Session["ProductsOnPage"];

            Session["BackUrl"] = "" + CategoryID.ToString() + "," + pageNumber.ToString() + "," + sort.ToString() + ((ProducerID > 0) ? "," + ProducerID.ToString() : "") + "," + Resources.Language.Category.ToLower() + ".aspx";
        }
    }

    private void RenderSortAnchor(int categoryId, int ProducerId, int page, int sortId, HtmlAnchor a)
    {
        StringBuilder url = new StringBuilder("");
        url.Append(categoryId);
        url.Append(",");
        url.Append(page);
        url.Append(",");
        url.Append(sortId);
        url.Append(",");
        if (ProducerId > 0)
        {
            url.Append(ProducerId);
            url.Append(",");
        }
        url.Append(Resources.Language.Category.ToLower() + ".aspx");
        a.HRef = url.ToString();
    }

    private void ProducersListDataBind()
    {
        rpProducers.DataSource = ProductsManager.Instance.GetProducersByCategory(CategoryID, ShopBLL.CommonTools.CurrentLanguageID);
        rpProducers.DataBind();
    }

    public void GenerateView(List<Products> productList, Category c, Panel pnl)
    {
        ShopModel.View v = ProductsManager.Instance.GetViewByID(c.ViewId.Value, CommonTools.CurrentLanguageID);
        StringBuilder sb = new StringBuilder();
        sb.Append(v.Template);

        int j = 0;
        Literal ltrl = new Literal();
        ltrl.ID = "ltr1"+j++;

        if (v.Template.IndexOf("##ItemTemplate#") != -1 && v.Template.IndexOf("#ItemTemplate##") != -1)
        {
            //wyciecie początkowej części do definicji jednego produktu
            ltrl.Text = v.Template.Substring(0, v.Template.IndexOf("##ItemTemplate#"));
            pnl.Controls.Add(ltrl); 
            // lista produktów
            // pobranie definicji wiersza tabeli
            string sItemTemplate = v.Template.Substring(v.Template.IndexOf("##ItemTemplate#") + 15, v.Template.IndexOf("#ItemTemplate##") - (v.Template.IndexOf("##ItemTemplate#") + 15));
            string itemTemplate = string.Empty;
            itemTemplate = sItemTemplate;
           // StringBuilder productsList = new StringBuilder();
            // zamiana znaczników na wartości i dodawanie do productsList
            int i = 1;
            int ilosc =0;
            foreach (Products product in productList)
            {
                ilosc = 0;
                Literal  l1, l2, l3;
                controls_ctrlproductcomparemanager_ascx compare;
                controls_ctrlRates rates;
                ltrl = new Literal();
                ltrl.ID = "ltr1" + j++;
                itemTemplate = itemTemplate.Replace("?#PriceNetto?",(product.SpecialOfferPriceNetto!=null?product.SpecialOfferPriceNetto.Value.ToString("F2"): product.PriceNetto.ToString("F2"))+" "+Resources.Language.Currency);
                itemTemplate = itemTemplate.Replace("?#PriceBrutto?", (product.SpecialOfferPriceBrutto != null ? product.SpecialOfferPriceBrutto.Value.ToString("F2") : product.PriceBrutto.ToString("F2")) + " " + Resources.Language.Currency);
                itemTemplate = itemTemplate.Replace("?#Name?", product.Name);
                itemTemplate = itemTemplate.Replace("?#SpecialPriceBrutto?", (product.SpecialOfferPriceBrutto !=null?product.PriceBrutto.ToString("F2")+" "+Resources.Language.Currency:""));
                itemTemplate = itemTemplate.Replace("?#SpecialPriceNetto?", (product.SpecialOfferPriceNetto != null ? product.PriceNetto.ToString("F2") + " " + Resources.Language.Currency : ""));
                itemTemplate = itemTemplate.Replace("?#NameUrl?", URLParser.ParseUrl(product.Name));
                itemTemplate = itemTemplate.Replace("?#ProductID?", product.IDproduct.ToString());
                itemTemplate = itemTemplate.Replace("?#AddToBasket?", @"<a href='#' onclick='addToBasket(" + product.IDproduct + ");return false'>" + Resources.Language.AddToBasket + "</a>");
                itemTemplate = itemTemplate.Replace("?#ShortDescription?", product.ShortDescription);
                itemTemplate = itemTemplate.Replace("?#PromotedText?", product.Promoted? Resources.Language.Promoted:"");
                itemTemplate = itemTemplate.Replace("?#Product?", Resources.Language.Product);

                if (product.Pictures.Count > 0)
                {
                    itemTemplate = itemTemplate.Replace("?#ThumbSrc?", product.Pictures[0].Miniature.VirtualPath.Replace("~", ""));
                }

                if (sItemTemplate.IndexOf("?#AddToCompare?") >= 0) ilosc++;
                if (sItemTemplate.IndexOf("?#Rates?") >= 0) ilosc++;

                if (ilosc == 0)
                {
                    ltrl.Text = itemTemplate;
                    pnl.Controls.Add(ltrl);
                }
                else if (ilosc == 1 && sItemTemplate.IndexOf("?#AddToCompare?") >= 0)
                {
                    l1 = new Literal();
                    l2 = new Literal();
                    l1.ID = "ltr" + j++;
                    l2.ID = "ltr" + j++;
                    compare = LoadControl("controls/ctrlProductCompareManager.ascx") as controls_ctrlproductcomparemanager_ascx;//new controls_ctrlproductcomparemanager_ascx();
                    compare.ID = "cmp" + j++;
                    compare.ProductID = product.IDproduct;
                    compare.SelectedProductsChanged += new EventHandler(pcmSelectedProducts_Changed);
                    l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#AddToCompare?"));
                    l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#AddToCompare?") + 15);
                    pnl.Controls.Add(l1);
                    pnl.Controls.Add(compare);
                    pnl.Controls.Add(l2);

                }
                else if (ilosc == 1 && sItemTemplate.IndexOf("?#Rates?") >= 0)
                {
                    l1 = new Literal();
                    l2 = new Literal();
                    l1.ID = "ltr" + j++;
                    l2.ID = "ltr" + j++;
                    rates = LoadControl("controls/ctrlRates.ascx") as controls_ctrlRates;//new controls_ctrlRates();
                    rates.ID = "rat" + j++;
                    rates.ProductID = product.IDproduct.ToString();
                    l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#Rates?"));
                    l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#Rates?") + 8);
                    pnl.Controls.Add(l1);
                    pnl.Controls.Add(rates);
                    pnl.Controls.Add(l2);
                }
                else if (ilosc == 2)
                {
                    l1 = new Literal();
                    l2 = new Literal();
                    l3 = new Literal();
                    l1.ID = "ltr" + j++;
                    l2.ID = "ltr" + j++;
                    l3.ID = "ltr" + j++;
                    compare = LoadControl("controls/ctrlProductCompareManager.ascx") as controls_ctrlproductcomparemanager_ascx;//new controls_ctrlproductcomparemanager_ascx();
                    compare.ID = "cmp" + j++;
                    compare.ProductID = product.IDproduct;
                    compare.SelectedProductsChanged += new EventHandler(pcmSelectedProducts_Changed);
                    rates = LoadControl("controls/ctrlRates.ascx") as controls_ctrlRates;//new controls_ctrlRates();
                    rates.ID = "rat" + j++;
                    rates.ProductID = product.IDproduct.ToString();
                    if (sItemTemplate.IndexOf("?#Rates?") < sItemTemplate.IndexOf("?#AddToCompare?"))
                    {
                        l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#Rates?"));
                        l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#Rates?") + 8, (itemTemplate.IndexOf("?#AddToCompare?") - (itemTemplate.IndexOf("?#Rates?") + 8)));
                        l3.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#AddToCompare?") + 15);

                        pnl.Controls.Add(l1);
                        pnl.Controls.Add(rates);
                        pnl.Controls.Add(l2);
                        pnl.Controls.Add(compare);
                        pnl.Controls.Add(l3);
                    }
                    else
                    {
                        l1.Text = itemTemplate.Substring(0, itemTemplate.IndexOf("?#AddToCompare?"));
                        l2.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#AddToCompare?") + 15, (itemTemplate.IndexOf("?#Rates?") - (itemTemplate.IndexOf("?#AddToCompare?") + 15)));
                        l3.Text = itemTemplate.Substring(itemTemplate.IndexOf("?#Rates?") + 8);

                        pnl.Controls.Add(l1);
                        pnl.Controls.Add(compare);
                        pnl.Controls.Add(l2);
                        pnl.Controls.Add(rates);
                        pnl.Controls.Add(l3);
                    }
                }

                //itemTemplate.Replace("?#AddToCompare?", "");
                //itemTemplate.Replace("?#Rates?", "");
                //productsList.Append(itemTemplate.ToString());
                //itemTemplate = string.Empty;
                itemTemplate=sItemTemplate;
                i++;
            }

            //sb.Replace(sItemTemplate, productsList.ToString());
            //sb.Replace("##ItemTemplate#", string.Empty);
           // sb.Replace("#ItemTemplate##", string.Empty);


            //wycięcie końcowej części po definicji produktu
            ltrl = new Literal();
            ltrl.ID = "ltr1" + j++;
            ltrl.Text = v.Template.Substring(v.Template.IndexOf("#ItemTemplate##")+15);
            pnl.Controls.Add(ltrl);
        }
        else
        {
            ltrl.Text = sb.ToString();
            pnl.Controls.Add(ltrl);
        }
        pnl.Visible = true;
       // lView.Text = sb.ToString();
    }

    #endregion METHODS

    #region EVENTS

    private void ButtonSearch_Click(ProductSearchCriteria criteria)
    {
        if (ProducerID > 0) { criteria.ProducerId = ProducerID; }// przy filtrowaniu wg producenta
        BindProduct(criteria, 1, 11);
        afterSearching = true;
        Session.Add("SearchParameter", criteria);
    }

    protected void ddlProductsOnPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Session["ProductsOnPage"] != null)
        {
            oldProductOnPage = Convert.ToInt32(Session["ProductsOnPage"]);
        }
        Session["ProductsOnPage"] = ddlProductsOnPage.SelectedValue;
    }

    protected void rpProducts_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (e.Item.DataItem != null)
            {
                Products product = (Products)e.Item.DataItem;
                if (product.Pictures.Count > 0)
                {
                    Image image = (Image)e.Item.FindControl("imgMiniature");
                    image.ImageUrl = product.Pictures[0].Miniature.VirtualPath;
                }
                else
                {
                    e.Item.FindControl("imgMiniature").Visible = false;
                }
            }
        }
    }

    protected void pcmSelectedProducts_Changed(object sender, EventArgs e)
    {
        if (this.Page.Master is _default)
        {
            if (Settings.ShowProductsToCompare)
            {
                controls_ctrlProductsToCompare ComparedProducts = (controls_ctrlProductsToCompare)(((_default)this.Master).FindControl("ctrlProductsToCompare"));

                if (ComparedProducts != null && ComparedProducts.BindControl)
                    ComparedProducts.ProductsBind();
            }
        }
    }

    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ProductsToCompare"] != null)
            ProductsToCompare = (List<int>)Session["ProductsToCompare"];
        else
            ProductsToCompare = new List<int>();

        if (Request.QueryString["ProducerId"] != null)
            ProducerID = Convert.ToInt32(Request.QueryString["ProducerId"]);

        if (Request.QueryString["CategoryId"] != null)
            CategoryID = Convert.ToInt32(Request.QueryString["CategoryId"]);

        if (Session["ProductsOnPage"] == null)
            Session["ProductsOnPage"] = ddlProductsOnPage.SelectedValue;

        if (Request.QueryString["Page"] != null)
            PageNumber = Convert.ToInt32(Request.QueryString["Page"]);

        if (Request.QueryString["Sort"] != null)
            Sort = Convert.ToInt32(Request.QueryString["Sort"]);

        if (this.Master is _default)
            ((_default)this.Master).OpenCategoryId = CategoryID;

        searchControl.ButtonSearchClick += new ProductSearchEventHandler(ButtonSearch_Click);
        searchControl.CategoryId = CategoryID;
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //CategoryList categoryList = (CategoryList)Session["CategoryList"];

        CategoryList categoryList = new CategoryList();
        categoryList.LoadCategory(ProductsManager.Instance.GetCategories(true, ShopBLL.CommonTools.CurrentLanguageID));

        if (categoryList != null)
        {
            CategoryListItem currentCategory = categoryList.FindByID(CategoryID);

            if (currentCategory != null)
            {
                CategoryName = currentCategory.Text;
                if (currentCategory.Items != null && currentCategory.Items.Count != 0)
                {
                    category.DataSource = currentCategory.Items;
                    category.DataBind();
                }
                else
                {
                    categoryListDiv.Visible = false;
                    producersListDiv.Visible = true;

                    if (!IsPostBack)
                    {
                        ProducersListDataBind();
                    }
                }
            }
        }

        ProductSearchCriteria args = new ProductSearchCriteria();


        if (Session["QuickSearchCriteria"] != null)
        {
            args = (ProductSearchCriteria)Session["QuickSearchCriteria"];
            CategoryName = Resources.Language.SearchResults;
            Session["SearchParameter"] = args;
            Session["QuickSearchCriteria"] = null;
        }
        else
            if (Session["SearchParameter"] != null && Sort > 10) //podczas przełączania strony po wyszukiwaniu
                args = (ProductSearchCriteria)Session["SearchParameter"];


        BindProduct(args, PageNumber, Sort);
        if (Sort > 10)
        {
            searchControl.SetSearchCriteriaValue(args);
        }
    }

    #endregion PAGE EVENTS
}
